package view.mh;

import helper.WeatherMathHelper;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

import metar.WindMetar;
import model.CityModel;
import model.CountryModel;
import model.WeatherModel;
import util.Config;
import view.ViewInterface;
import controller.Actions;
import controller.Controller;


/**
 * Wetterstation-GUI
 * @author Michael Hejna
 * @version 3.5 - final
 */
public class WeatherGUI implements Observer, ViewInterface{

		
		
		
		final Dimension d = new Dimension(200, 100);
		final Font f = new Font("Arial", Font.BOLD, 14);
		final Dimension minimumSize = new Dimension(200,100);
		
		ArrayList<CountryModel> countryList;
		JFrame frame = new JFrame("JWeatherStation RC1 (c) 2013 by alfatraining");
		public static int timer = 0;
			
		
		
		
		private Controller control;

		private JPanel panel;
		private JPanel topic;
		private JTextField label;
		private JPanel upperWindow;
		private JPanel mainWindowPanel;
		private JPanel upperMainWindow;
		private JPanel selectingMenu;
		private JComboBox country;
		private JComboBox airport;
		private JPanel lowerPanel;
		private JButton aktualizing;
		private JButton printing;
		private JButton exiting;
		private JPanel view;
		private JPanel upperView;
		private JPanel lowerView;
		private JPanel upperUpperView;
		private JPanel lowerUpperView;
		private JTextField city;
		private JTextField temperature;
		private JTextField wind;
		private JTextField cloudiness;
		private JTextField visibility;
		private ImageIcon icon;
		private JTextField airPressure;
		private JMenuBar menuebar;
		private JMenu menue;
		private JMenuItem credits;
		private CredWindow credWindow;
		private JMenu file;
		private JMenuItem print;
		private JMenuItem exit;
		private JLabel helper;

		private ArrayList<CountryModel> countryList2;

		private ArrayList<CityModel> cityList;
		private WeatherModel weather;
		private String[] countries;
		private String[] cities;
		
		public WeatherGUI(Controller controller) {
			setController(controller);
			

			
			try {
				fenster();
			} catch (ClassNotFoundException e) {
				
				e.printStackTrace();
			} catch (InstantiationException e) {
			
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				
				e.printStackTrace();
			} catch (UnsupportedLookAndFeelException e) {
			
				e.printStackTrace();
			}
			build();
		}
		
		
	public void fenster() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{ 

			/**
			 * 
			 * Erstellung des Layouts
			 * 
			 */
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			frame.setSize(1000, 400);
			frame.setLocation(500, 200);
			
			frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Config.APP_DIR + File.separator+"resources"+File.separator+"weather_sun.png"));
			
			panel = new JPanel();
		
			panel.setLayout(new BorderLayout());
			
	
			/**
			 * 
			 * "Überschrift"
			 */
			
			topic = new JPanel();
			
			label = new JTextField("Wetterstation light (c) 2013 by Java Group Enterprises");
			
			label.setSize(100, 100);
			label.setEditable(false);
			topic.add(label);
			
			Border border = new LineBorder(Color.BLACK);
			topic.setBorder(border);
			
			upperWindow = new JPanel(new BorderLayout());
			upperWindow.add(topic, BorderLayout.NORTH);
			upperWindow.add(mainWindowPanel(), BorderLayout.SOUTH);
			
			
			panel.add(upperWindow, BorderLayout.NORTH);
			
			panel.add(lowerMenue(), BorderLayout.SOUTH);
			panel.add(results(), BorderLayout.CENTER);
			
			
			frame.setJMenuBar(createMenue());
			frame.add(panel);
			build();
		}
		
		
		@SuppressWarnings({ "rawtypes", "unchecked" })

		public JPanel mainWindowPanel(){ 

	
			mainWindowPanel = new JPanel(new BorderLayout());
			upperMainWindow = new JPanel(new BorderLayout());
			
			/** 
			 * Auswahlmenüs
			 */
			
			selectingMenu = new JPanel(new FlowLayout());

			countryList2 = new ArrayList<CountryModel>();
			
			country = new JComboBox();
			
			((JComponent) country).setToolTipText("Bitte wählen Sie das Land aus.");
			((JComponent) country).setFont(f);

			country.setToolTipText("Bitte wählen Sie das Land aus.");
			country.setFont(f);
			control.addListener(country, Actions.GET_CITIES);

			
			airport = new JComboBox();
			airport.setToolTipText("Bitte wählen Sie den Flughafen aus.");
			airport.setFont(f);
			control.addListener(airport, Actions.GET_CURRENT_WEATHER);
			airport.setEnabled(false);

			selectingMenu.add(country, FlowLayout.LEFT);
			selectingMenu.add(airport);
			
			
			
			upperMainWindow.add(selectingMenu, BorderLayout.NORTH);
		
			mainWindowPanel.add(upperMainWindow, BorderLayout.NORTH);
			return mainWindowPanel;
		}
	
		
		public JPanel lowerMenue(){
			
			lowerPanel = new JPanel(new FlowLayout());
			
			aktualizing = new JButton("Aktualisieren");
			aktualizing.addActionListener(this.control.getActionListener(Actions.GET_CURRENT_WEATHER));
			
			aktualizing.setToolTipText("Aktualisierung der Wetterdaten");
			
			aktualizing.setFont(f);
			
			
			printing = new JButton("Drucken");
			printing.addActionListener(this.control.getActionListener(Actions.PRINT));
			

			printing.setFont(f);
			printing.setToolTipText("druckt das aktuelle Wetter aus");
			
			
			/**
			 * 
			 * Aus Gründen der Usability deaktiviert
			 * 
			 */
			
//			exiting = new JButton("Beenden");
//			exiting.addActionListener(new ActionListener() {
//				
//				@Override
//				public void actionPerformed(ActionEvent e) {
//					// TODO Auto-generated method stub
//					System.exit(0);
//				}
//			});
//			exiting.setBackground(Color.RED);
//			exiting.setFont(f);
//			exiting.setToolTipText("beendet das aktuelle Programm");
				
				
			lowerPanel.add(aktualizing);
			lowerPanel.add(printing);
			
			Border border = new LineBorder(Color.BLACK);
			lowerPanel.setBorder(border);
			return lowerPanel;
			
		}

		
		
		public JPanel results (){
			
			// Hier wird das Wetter ausgegeben
			
			view = new JPanel(new BorderLayout());
			
			upperView = new JPanel(new BorderLayout());
			lowerView = new JPanel(new FlowLayout(FlowLayout.CENTER));
			
			/**
			 * 
			 * Textfeld-Reihe
			 * 
			 */
			
			
			upperUpperView = new JPanel(new BorderLayout(20, 20));
			lowerUpperView = new JPanel(new BorderLayout(20, 20));
			
			city = new JTextField("Flughafen", 20);
			
			city.setFont(f);
			city.setToolTipText("Flughafen-Kennung");
			city.setEditable(false);
			city.setEnabled(true);
			
			
			temperature = new JTextField("Temperatur", 20);
			temperature.setToolTipText("Ausgabe der Temperatur in Celsius und Fahrenheit");
			
			temperature.setFont(f);
			temperature.setEditable(false);
			temperature.setEnabled(true);
			
			airPressure = new JTextField("Luftdruck ", 20);
			airPressure.setToolTipText("Luftdruck in Hektopascal");
			airPressure.setFont(f);
			airPressure.setEditable(false);
			airPressure.setEnabled(true);
						
			
			wind = new JTextField("Winddaten", 20);
			wind.setToolTipText("Windstärke und -richtung");
			wind.setFont(f);
			wind.setEditable(false);
			wind.setEnabled(true);
		
			
			cloudiness = new JTextField("Bewölkung", 20);
			cloudiness.setToolTipText("Bewölkung");
			cloudiness.setFont(f);
			cloudiness.setEditable(false);
			cloudiness.setEnabled(true);
			
			
			visibility = new JTextField("Sichtweite", 20);
			visibility.setToolTipText("Sichtweite in Metern");
			visibility.setFont(f);
			visibility.setEditable(false);
			visibility.setEnabled(true);
			
			
			
			/**
			 * 
			 * kleines Icon-Schmankerl
			 * 
			 */
			
			
			helper = new JLabel();
			helper.setIcon(icon);
					
			upperUpperView.add(city, BorderLayout.WEST);
			upperUpperView.add(temperature, BorderLayout.CENTER);
			upperUpperView.add(airPressure, BorderLayout.EAST);
			
			lowerUpperView.add(cloudiness, BorderLayout.WEST);
			lowerUpperView.add(wind, BorderLayout.CENTER);
			lowerUpperView.add(visibility, BorderLayout.EAST);
		
			
			upperView.add(upperUpperView, BorderLayout.NORTH);
			upperView.add(lowerUpperView, BorderLayout.SOUTH);
			
			lowerView.add(helper);
			view.add(upperView, BorderLayout.NORTH);
			view.add(lowerView);
			view.setBackground(Color.BLUE);
			
		
			
			return view;
		}

		/**
		 * 
		 * Erstellung der Menüleiste
		 * @return
		 */
		public JMenuBar createMenue(){
			
			menuebar = new JMenuBar();
			
			
			file = new JMenu("Datei");
			
			print = new JMenuItem("Drucken...", new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"printer_3.png"));
			print.addActionListener(this.control.getActionListener(Actions.PRINT));
			
			
			exit = new JMenuItem("Beenden", new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"skull.png"));
			exit.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					
					System.exit(0);
				}
			});
			
			file.add(print);
			file.add(exit);
			
			menue = new JMenu("Hilfe");
			
			credits = new JMenuItem("Über...", new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"question.png"));
			credits.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
				
					credWindow = new CredWindow();
					credWindow.credits();
				}
			});
			
		
			menue.add(credits);
				
			menuebar.add(file);
			menuebar.add(menue);
			
			
			return menuebar;
		}
		

		/**
		 * 
		 * Datenausgabe
		 * 
		 * 
		 */
		public void dataOutput(){
			
			visibility.setText(String.valueOf(weather.getVisibility())+" Meter");
			city.setText(weather.getInfo());
			temperature.setText(weather.getTemperature() + "°C, "+ WeatherMathHelper.convertCelsius2Fahrenheit(weather.getTemperature())+ "°F");
			wind.setText(weather.getWind().getSpeedKnot() + " Knoten - " + WindMetar.windDirectionAsString(weather.getWind().getDirection()));
			airPressure.setText(String.valueOf(weather.getAirPressure())+" hPa");
			
			String clouds = weather.getCloudiness().substring(0, 3);	// Hilfsvariable
			
			
			/**
			 * 
			 * Bewölkung in "Reinschrift"
			 * 
			 */
			

			if (clouds.contains("SKC") || clouds.contains("CAV") ){
				cloudiness.setText("wolkenlos");
				icon = new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"sunny.png");
				helper.setIcon(icon);
			}
			
			if (clouds.contains("NSC") ){
				cloudiness.setText("heiter");
				icon = new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"heiter.png");
				helper.setIcon(icon);
			}
			
			if (clouds.contains("FEW") ){
				cloudiness.setText("leicht bewölkt");
				icon = new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"bewoelkt.png");
				helper.setIcon(icon);
			}
			
			if (clouds.contains("SCT") ){
				cloudiness.setText("bewölkt");
				icon = new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"starkbewoelkt.png");
				helper.setIcon(icon);
			}
			
			if (clouds.contains("BKN") ){
				cloudiness.setText("dicht bewölkt");
				icon = new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"starkbewoelkt.png");
				helper.setIcon(icon);
			}
			
			if (clouds.contains("OVC") ){
				cloudiness.setText("bedeckt");
				icon = new ImageIcon(Config.APP_DIR + File.separator+"resources"+File.separator+"rainy.png");
				helper.setIcon(icon);
			}
		}
				
				
		/**
		 * 
		 * Schnittstellen
		 * 
		 * 
		 */
		
		/**
		 * eingehender Datenstrom
		 */
		@SuppressWarnings("unchecked")
		@Override
		public void update(Observable arg0, Object arg1) {
		
			
//			try {
				if(arg1 instanceof ArrayList<?>){
					if(((ArrayList<CountryModel>) arg1).get(0) instanceof CountryModel){
						countryList2 = (ArrayList<CountryModel>) arg1;
						
						for(int i = 0; i < countryList2.size(); i++){
							

							country.addItem(((ArrayList<CountryModel>) arg1).get(i));
							
						}	
							
							
						
					}
					if(((ArrayList<CityModel>) arg1).get(0) instanceof CityModel){
						cityList = (ArrayList<CityModel>) arg1;
						airport.setEnabled(true);
						cities = new String[cityList.size()];
						airport.removeAllItems();
						for(int i = 0; i <  ((ArrayList<CityModel>)arg1).size(); i++){

							airport.addItem(((ArrayList<CityModel>) arg1).get(i));
							
						}
	
					}
				}
				
				if(arg1 instanceof WeatherModel){
					weather = (WeatherModel) arg1;
					dataOutput();
				}
				
				

		}


		@Override
		public void setController(Controller control) {
			this.control = control;			
		}


		@Override
		public void build() {
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
		}


}	


	

